package task

import (
	"file_explorer/common/log"

	"fyne.io/fyne/v2/container"
)

type FeTaskManager struct {
	tabTaskMap  map[*container.TabItem][]FeTask // tab任务，随tabContext删除而取消
	globalTasks []FeTask                        // 全局任务，tab关闭也在后台运行
}

// 获取全局任务数量
func (manager *FeTaskManager) GlobalTaskLength() int {
	return len(manager.globalTasks)
}

// 获取全局任务
func (manager *FeTaskManager) GetGlobalTask(index int) FeTask {
	return manager.globalTasks[index]
}

// 提交全局任务
func (manager *FeTaskManager) SubmitGlobalTask(task FeTask) {
	log.Debug("submit global task, label=%v", task.GetLabel())
	manager.globalTasks = append(manager.globalTasks, task)
	go task.start()
}

// 移除全局任务，若未完成则取消
func (manager *FeTaskManager) DeleteGlobalTask(task FeTask) {
	log.Debug("delete global task, label=%v", task.GetLabel())
	for index, item := range manager.globalTasks {
		if item == task {
			task.Cancel()
			manager.globalTasks = append(manager.globalTasks[:index], manager.globalTasks[index+1:]...)
			return
		}
	}
}

// 提交tab任务
func (manager *FeTaskManager) SubmitTabTask(tabItem *container.TabItem, task FeTask) {
	log.Debug("submit tab task, tab=%v, label=%v", tabItem.Text, task.GetLabel())

	if manager.tabTaskMap[tabItem] == nil {
		manager.tabTaskMap[tabItem] = make([]FeTask, 0)
	}
	manager.tabTaskMap[tabItem] = append(manager.tabTaskMap[tabItem], task)
	go task.start()
}

// 移除tab任务
func (manager *FeTaskManager) DeleteTabTask(tabItem *container.TabItem, task FeTask) {
	log.Debug("delete tab task, tab=%v, label=%v", tabItem.Text, task.GetLabel())

	if manager.tabTaskMap[tabItem] == nil {
		return
	}
	for index, item := range manager.tabTaskMap[tabItem] {
		if task == item {
			task.Cancel()
			tasks := manager.tabTaskMap[tabItem]
			tasks = append(tasks[:index], tasks[index+1:]...)
			return
		}
	}
}

// 清空tab下所有任务
func (manager *FeTaskManager) ClearTabTasks(tabItem *container.TabItem) {
	log.Debug("clear tab task, tab=%v", tabItem.Text)

	if manager.tabTaskMap[tabItem] == nil {
		return
	}
	for _, item := range manager.tabTaskMap[tabItem] {
		item.Cancel()
	}
	manager.tabTaskMap[tabItem] = nil
}

func NewFeTaskManager() *FeTaskManager {
	return &FeTaskManager{
		tabTaskMap:  make(map[*container.TabItem][]FeTask),
		globalTasks: make([]FeTask, 0),
	}
}
